package com.kaia.shoebox.loader;

import java.util.List;

import android.content.AsyncTaskLoader;
import android.content.Context;

import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.kaia.shoebox.db.dao.TodoItem;

public class TodoListLoader extends AsyncTaskLoader<List<TodoItem>> {

	private RuntimeExceptionDao<TodoItem, Integer> mDao;
	private PreparedQuery<TodoItem> mQuery;
	private List<TodoItem> mList;

	public TodoListLoader(Context context,
			RuntimeExceptionDao<TodoItem, Integer> dao,
			PreparedQuery<TodoItem> query) {
		super(context);
		mDao = dao;
		mQuery = query;
	}

	@Override
	public List<TodoItem> loadInBackground() {
		List<TodoItem> result = null;

		if (mQuery != null) {
			result = mDao.query(mQuery);
		} else {
			result = mDao.queryForAll();
		}

		return result;

	}

	@Override
	public void deliverResult(List<TodoItem> data) {
		if (isReset()) {
			if (data != null) {
				onReleaseResources(data);
			}
		}

		List<TodoItem> oldData = mList;
		mList = data;

		if (isStarted()) {
			super.deliverResult(data);
		}

		if (oldData != null && !oldData.isEmpty()) {
			onReleaseResources(oldData);
		}
	}

	@Override
	protected void onStartLoading() {
		if (mList != null) {
			deliverResult(mList);
		} else {
			forceLoad();
		}
	}

	@Override
	protected void onStopLoading() {
		cancelLoad();
	}

	@Override
	protected void onReset() {
		super.onReset();

		onStopLoading();

		if (mList != null) {
			onReleaseResources(mList);
			mList = null;
		}
	}

	private void onReleaseResources(List<TodoItem> mList2) {
		// Nothing to do
	}

}
